package com.cats.bi.service.impl;

import com.cats.bi.dao.CommMapper;
import com.cats.bi.enums.DataEnum;
import com.cats.bi.pojo.dto.DimensionDto;
import com.cats.bi.pojo.dto.MeasureDto;
import com.cats.bi.pojo.dto.ViewDto;
import com.cats.bi.service.CommService;
import com.cats.bi.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author duxiaobo
 * @date 2021/8/1510:43 上午
 */
@Service
public class CommServiceImpl implements CommService {

    private final String PREFIX = "_";

    @Autowired
    private CommMapper commMapper;


    @Override
    public Map<String, Object> getMap(String sql) {
        return commMapper.getMap(sql);
    }

    @Override
    public List<Map<String, Object>> getList(String sql) {
        return commMapper.getList(sql);
    }

    @Override
    public ViewDto getDataInList(ViewDto viewDto) {
        if (!CollectionUtils.isEmpty(viewDto.getDimensions())) {
            viewDto.getDimensions().forEach(dimensionDto -> {
                Object[] objects = getDimensionDataInList(viewDto.getData(), dimensionDto);
                dimensionDto.setData(Arrays.asList(objects));
            });
        }

        if (!CollectionUtils.isEmpty(viewDto.getMeasures())) {
            viewDto.getMeasures().forEach(measureDto -> {
                Object[] objects = getMeasureDataInList(viewDto.getData(), measureDto);
                measureDto.setData(Arrays.asList(objects));
            });
        }
        return viewDto;
    }

    @Override
    public Object[] getMeasureDataInList(List<Map<String, Object>> list, MeasureDto measureDto) {
        return ListUtils.getData(list, measureDto.getSecondCalculation().getType() + PREFIX + measureDto.getCalculation().getType() + PREFIX + measureDto.getEntityKey() + PREFIX + measureDto.getItemKey(), measureDto.getDataEnum().getDefaultValue());
    }

    @Override
    public Object[] getDimensionDataInList(List<Map<String, Object>> list, DimensionDto dimensionDto) {
        return ListUtils.getData(list, dimensionDto.getEntityKey() + PREFIX + dimensionDto.getItemKey(), dimensionDto.getDataEnum().getDefaultValue());
    }
}
